"""
User Controller
Handles business logic related to users with Redis caching
"""

from app import RedisManager
from app.models.user import User
from app import db
from flask import g
from app.session_utils import SessionManager

class UserController:
    """Controller for user-related operations with Redis caching"""
    
    @staticmethod
    def get_user_with_cache(user_id):
        """
        Retrieve user details with Redis caching
        """
        # Try to get from session cache first
        cached_user = SessionManager.get_cached_user_info(user_id)
        if cached_user:
            return cached_user
        
        # If not in cache, get from database
        user = User.query.get(user_id)
        if user:
            user_data = {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'status': user.status,
                'background_image': user.background_image,
                'avatar': user.avatar,
                'user_group': user.user_group,
                'created_at': user.created_at.isoformat() if user.created_at else None,
                'updated_at': user.updated_at.isoformat() if user.updated_at else None
            }
            
            # Cache the user data
            SessionManager.cache_user_info(user_id)
            return user_data
        
        return None
    
    @staticmethod
    def create_user(username, email, password, current_user_id=None, **kwargs):
        """
        Create a new user and invalidate related caches
        """
        user = User(
            username=username,
            email=email,
            password=password,
            status=kwargs.get('status', 1),
            background_image=kwargs.get('background_image'),
            avatar=kwargs.get('avatar'),
            user_group=kwargs.get('user_group', 'user'),
            created_by=current_user_id
        )
        
        db.session.add(user)
        db.session.commit()
        
        return user
    
    @staticmethod
    def update_user(user_id, current_user_id=None, **kwargs):
        """
        Update user information and invalidate cache
        """
        user = User.query.get(user_id)
        if not user:
            return None
        
        # Update user fields
        for key, value in kwargs.items():
            if hasattr(user, key):
                setattr(user, key, value)
        
        # Set the updater
        user.updated_by = current_user_id
        
        db.session.commit()
        
        # Update user cache
        SessionManager.update_cached_user_info(user_id)
        
        return user
    
    @staticmethod
    def delete_user(user_id, current_user_id=None):
        """
        Delete user and invalidate cache
        """
        user = User.query.get(user_id)
        if not user:
            return False
        
        # Set the deleter
        user.deleted_by = current_user_id
        user.deleted_at = db.func.current_timestamp()
        
        db.session.commit()
        
        # User info is automatically deleted from cache when session is deleted
        return True
    
    @staticmethod
    def get_user_recent_submissions(user_id, count=10):
        """
        Get user's recent submissions from Redis
        """
        return RedisManager.get_user_recent_submissions(user_id, count)